﻿declare var WebUploader: any;
$(function () {
    var $uploader = $("#uploader");
    var $upBtns = $uploader.find(".btns div");
    //已经进入队列的文件总大小，用于进度显示 以及已经完成个数。
    //由于webuploader获取状态信息的结果不准确，所以自己维护一下。
    var QueuedCount = 0, QueuedSize = 0, DoneCount = 0, DoneSize = 0;
    //立即输出总进度，概要信息
    function rendZprogress() {
        $uploader.find(".statusBar .progress-bar").css('width', (DoneSize / QueuedSize * 100).toFixed(2) + '%');
        var stat = uploader.getStats()
        $uploader.find(".statusBar .info").text(`文件情况：${DoneCount}/${QueuedCount}个，总大小${WebUploader.formatSize(QueuedSize)}`)
    }

    var uploader = WebUploader.create({
        swf: '/Scripts/webuploader/Uploader.swf',
        server: '/api/sys/FileUpload2',
        fileNumLimit: 1000000,
        dnd: '#uploader',
        pick: '#btnPicker,#btnPickerdir',
        resize: false
    });
    setTimeout(function () {
        $("#btnPickerdir").find("input").attr({ directory: "true", mozdirectory: "true", webkitdirectory: "true" })
    }, 300);

    //初始化时，要显示一下情况
    rendZprogress()
    // 当有文件被添加进队列的时候
    var $list = $("#uploader .filelist");
    uploader.on('fileQueued', function (file) {
        console.log(file.source.source.webkitRelativePath);
        let iconHtml = `<div class="file-icon file-icon-lg " data-type="${file.ext}"></div>`;
        let liHtml = ` 
<li id='${file.id}' title='${file.name}'>
    <span class="title"contenteditable="true">${file.name}</span>
    <div class="fileicon">#iconHtml#</div>
    <div class="tool-trash"><span class="glyphicon glyphicon-trash pull-right"></span></div>
    <div class="progress"><div class="progress-bar"></div></div>
</li>`;
        //如果是图像，则插入缩略图，其它插入一个默认背景色
        if (/^image*\//.test(file.type)) {
            uploader.makeThumb(file, function (error, ret) {
                var $li = $("<li>");
                if (error) {
                    iconHtml = ('预览错误');
                } else {
                    iconHtml = `<img alt='' src='${ret}' />`;
                }
                $list.append(liHtml.replace("#iconHtml#", iconHtml));
            }, 80, 70);
        } else {
            $list.append(liHtml.replace("#iconHtml#", iconHtml));
        }
        //统计一下总大小，总文件数
        QueuedSize += file.size;
        QueuedCount++;

        rendZprogress()
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function (file, percentage) {
        //单个文件 进度
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');
        $percent.css('width', percentage * 100 + '%');
    });
    //成功
    uploader.on('uploadSuccess', function (file) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');
        $percent.css('width', 100 + '%');
        DoneSize += file.size
        DoneCount++;
        rendZprogress();

        //成功后，不能再删除了
        $li.find(".tool-trash").remove();
        $li.find(".title").prop("contenteditable", 'false');
    });
    //失败则显示红进度条，且进度走满
    uploader.on('uploadError', function (file) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');
        $percent.addClass('progress-bar-danger').css('width', 100 + '%');
        //失败也表示无法上传了。那么也算完成数增加
        DoneCount++;
    });
    //每一个文件成功时
    uploader.on('uploadComplete', function (file) {

    });
    //上传之前，要提交一下参数.默认似乎有4，5个参数了
    uploader.on('uploadBeforeSend', function (obj, data, header) {
        console.log(obj.file.source.source.webkitRelativePath);
        data.sslb = $("#selSSLB").val();
        data.sszy = $("#selSSZY").val();
        data.ssyt = $("#selSSYT").val();
    });
    var $btnUp = $("#btnUpload");
    $btnUp.click(function () {
        //如果有待传文件
        if (QueuedCount > DoneCount) {
            uploader.upload();
        }
    });
    var $btnStop = $("#btnStop");
    $btnStop.click(function () {
        //暂停并切换按钮
        uploader.stop(true);
    });
    //删除当前未完成的文件时
    $uploader.on("click", ".glyphicon-trash", function () {
        var $li = $(this).parents('li');
        var fid = $li.attr("id");
        var file = uploader.getFile(fid);
        //减小这几个变量
        QueuedCount-- , QueuedSize -= file.size;
        DoneCount--;
        //移除文件
        uploader.removeFile(fid, true);
        $li.remove();
        //更新状态
        rendZprogress()
    });

    //重置
    $("#btnReset").click(function () {
        QueuedCount = 0, QueuedSize = 0, DoneCount = 0, DoneSize = 0;
        uploader.reset();
        rendZprogress();
        $list.empty();
    });
});